package com.xsprite.managesys.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.xsprite.managesys.bean.XlsxFileBean;
import com.xsprite.managesys.log.LogManager;
import com.xsprite.managesys.service.XlsxFileManager;

public class UploadFileServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	public UploadFileServlet() {
		super();
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.service(req, resp);
		final String allowExtNames = "xlsx,xls";
		String basePath = this.getServletContext().getRealPath("/upload/");
		ServletFileUpload servletFileUpload = createServletFileUpload(basePath);
		String userid = req.getSession().getAttribute("userid").toString();
		List<FileItem> fileItems = null;
		try {
			fileItems = servletFileUpload.parseRequest(req);
			uploadFile(allowExtNames, basePath, userid, fileItems);
			XlsxFileManager.getInstance().reloadExcelDatas();
		} catch (Exception ex) {
			LogManager.getInstance().log4j("userid = " + userid + " " + ex.getMessage());
		}
		forwardTo("/view/workbench.jsp");
	}

	private void uploadFile(final String allowExtNames, String basePath, String userid, List<FileItem> fileItems) throws Exception, FileUploadException {
		for (FileItem fileItem : fileItems) {
			String filePath = fileItem.getName();
			if (filePath == null || filePath.trim().length() == 0) {
				continue;
			}
			String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
			String extName = filePath.substring(filePath.lastIndexOf(".") + 1);
			if (allowExtNames.indexOf(extName) != -1) {
				fileItem.write(new File(basePath + File.separator + fileName));
				logSuccessInfo(fileItem, userid);
				XlsxFileBean bean = new XlsxFileBean();
				bean.setFilename(fileName);
				bean.setFileSize(fileItem.getSize());
				bean.setFilePath(basePath + File.separator + fileName);
				bean.setUploadDate(System.currentTimeMillis());
				XlsxFileManager.getInstance().addBean(bean);
			} else {
				throw new FileUploadException("file type is not allowed");
			}
		}
	}
	
	private void logSuccessInfo(FileItem item, String userid){
		LogManager.getInstance().log4j("userid=" + userid + ",上传文件:" + item.getName() + "成功!");
	}

	private ServletFileUpload createServletFileUpload(String basePath) {
		int sizeThreshold = 1024 * 6;
		File repository = new File(basePath);
		long sizeMax = 1024 * 1024 * 2;
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
		diskFileItemFactory.setRepository(repository);
		diskFileItemFactory.setSizeThreshold(sizeThreshold);
		ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
		servletFileUpload.setSizeMax(sizeMax);
		return servletFileUpload;
	}
}
